import React, { useState, useRef } from 'react';
import { Button, Select, Popconfirm, FormInstance } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { 
  getBrandList, 
  doCreateBrand, 
  deleteBrandBatch, 
  deleteBrand, 
  updateBrand 
} from '@/services/stock-goods/api';
import BrandDetail from './Detail';
import OptForm from './OptForm';
import { OptType } from '@/utils/constants';
import { MsgType, showMsg } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import BreadcrumbDept from '@/components/BreadcrumbDept';

const BrandList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<STOCKGOODSAPI.BrandItem>({});
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  // 批量操作ids
  const [brandIds, setBrandIds] = useState<string[]>([]);

  // 操作类型
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const [searchFlag, setSearchFlag] = useState<number>(0);
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色


  // 表格列
  const columns: ProColumns<STOCKGOODSAPI.BrandItem>[] = [
    {
      title: '查询范围',
      hideInTable: true,
      dataIndex: 'flag',
      valueType: 'select',
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return <Select onChange={(value) => {
          setSearchFlag(value);
          if (value === 2 || value === 3) {
            formRef.current?.setFieldsValue({
              key_words: null
            })
          }
        }} placeholder="请选择">
          <Select.Option key={0} value={0}>全部</Select.Option>
          <Select.Option key={1} value={1}>指定品牌</Select.Option>
          <Select.Option key={2} value={2}>仅包含商品的品牌</Select.Option>
          <Select.Option key={3} value={3}>不包含商品的品牌</Select.Option>
        </Select>
      }
    },
    {
      title: '品牌名称',
      dataIndex: 'key_words',
      hideInTable: true,
      hideInSearch: [2, 3].includes(searchFlag)
    },
    {
      title: '品牌名称',
      dataIndex: 'brand_name',
      search: false
    },
    {
      title: '检索码',
      dataIndex: 'brand_py',
      search: false,
      width: 120
    },
    {
      title: '品牌下商品种类',
      dataIndex: 'num',
      search: false,
      align: 'right',
      width: 120
    },
    {
      title: '操作',
      align: 'center',
      width: 120,
      valueType: 'option',
      render: (_, record) => [
        <PermissionControl key="view" action_id="200202003">
          <a onClick={() => {
            setDetailVisible(true);
            setCurrentRow(record);
          }}>查看</a>
        </PermissionControl>,

        <PermissionControl key="edit" action_id="200202004">
          <a onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
            setOptType(OptType.EDIT);
          }}>编辑</a>
        </PermissionControl>,

        record.num === 0 &&  <PermissionControl key="delete" action_id="200202005">
          <Popconfirm 
            placement="topRight"
            title="您即将删除品牌，是否继续？"
            onConfirm={() => {
              handleDelete(record.brand_id as string)
            }}
            okText="确认删除"
            cancelText="再想想">
            <a>删除</a>
          </Popconfirm>
        </PermissionControl>
      ]
    }
  ];

  /**
   * 添加品牌
   * @param fields 
   * @returns 
   */
  const handleAdd = async (fields: STOCKGOODSAPI.BrandItem) => {
    try {
      let data = null;
      if (optType === OptType.ADD) {
        data = await doCreateBrand({ ...fields });
      } else {
        data = await updateBrand({ ...fields });
      }
      showMsg('已保存', MsgType.SUCCESS);
      return data;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return null;
    }
  };

  /**
   * 批量删除品牌
   * @returns 
   */
  const handleDeleteBatch = async () => {
    try {
      await deleteBrandBatch(brandIds);
      showMsg('删除成功！', MsgType.SUCCESS);
      setBrandIds([]);
      actionRef.current?.reload();
      actionRef.current?.clearSelected?.();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  /**
   * 单个删除品牌
   * @returns 
   */
  const handleDelete = async (brand_id: string) => {
    try {
      await deleteBrand(brand_id);
      showMsg('删除成功！', MsgType.SUCCESS);
      actionRef.current?.reload();
      actionRef.current?.clearSelected?.();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  /**
   * 复选框
   * @param selectedRowKeys 
   * @param selectedRows 
   * @returns 
   */
  const onRowChange = (selectedRowKeys: React.Key[], selectedRows: STOCKGOODSAPI.BrandItem[]) => {
    if (!selectedRows.length) {
      setBrandIds([]);
      return
    }
    const rows = selectedRows.map(item => {
      return item.brand_id;
    });
    
    setBrandIds(rows as string[]);
  }

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<STOCKGOODSAPI.BrandItem, STOCKGOODSAPI.BrandItem & COMMON.PageParams>
        rowKey='brand_id'
        actionRef={actionRef}
        formRef={formRef}
        bordered
        search={{
          span: 6,
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [<PermissionControl key="search" action_id="200202000">{dom}</PermissionControl>]
          }
        }}
        request={async (params) => {
          try {
            params = Object.assign({}, params, { flag: searchFlag });
            const data: STOCKGOODSAPI.BrandItemList = await getBrandList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}

        rowSelection={{
          columnWidth: 80,
          onChange: onRowChange,
          getCheckboxProps: (record: STOCKGOODSAPI.BrandItem) => ({
            disabled: record.num as number > 0
          })
        }}
        options={false}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="200202001">
                  <Button 
                  onClick={() => {
                    handleModalVisible(true);
                    setCurrentRow({} as STOCKGOODSAPI.BrandItem);
                    setOptType(OptType.ADD);
                  }} 
                  icon={<PlusOutlined />} 
                  type="primary">
                  新增
                </Button>
                </PermissionControl>
              },
              {
                key: 'batchDelete',
                label: <PermissionControl action_id="200202002">
                    <Popconfirm 
                      disabled={!brandIds.length}
                      title="您即将删除选中的品牌，是否继续？"
                      onConfirm={handleDeleteBatch}
                      okText="确认删除"
                      cancelText="再想想">
                      <Button disabled={!brandIds.length} icon={<DeleteOutlined />} type="primary">
                      批量删除
                      </Button>
                    </Popconfirm>
                </PermissionControl> 
              }
            ]
          }
        }}

        pagination={{
          showQuickJumper: true
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.brand_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.brand_id === clickRow ? 'tableRowClick' : ''
        }}
      />

      {
        detailVisible && <BrandDetail 
          handleModalVisible={setDetailVisible}
          record={currentRow}
        />
      }

      {
        createModalVisible && <OptForm 
          actionRef={actionRef}
          handleAdd={handleAdd}
          handleModalVisible={handleModalVisible}
          record={currentRow}
          optType={optType}
        />
      }  
      
    </PageContainer>
  );
};
export default BrandList;
